<template>
  <div class="visitor-management">
    
    <!-- 统计卡片区域 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-label">所有访客</div>
        <div class="stat-value">{{ vtatolnum}}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">当前访客</div>
        <div class="stat-value">{{vingnum}}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">待访来客</div>
        <div class="stat-value">{{ vednum }}</div>
      </div>
      <!-- 新增访客卡片 -->
      <div class="stat-card add-card" @click="openAddDialog">
        <div class="stat-label">新增访客</div>
        <div class="stat-icon">+</div>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-input
        placeholder="请输入姓名/手机号搜索"
        style="width: 240px;"
        v-model="visitorTitle"
      />
      <el-button type="primary" icon="el-icon-search" @click="getVisitorList(1)"></el-button>
    </div>

    <!-- 访客表格 -->
    <el-table :data="tableData" border style="width: 100%; margin-bottom: 20px;">
      <el-table-column prop="visitorName" label="姓名" />
      <el-table-column prop="visitorSex" label="性别" />
      <el-table-column prop="visitorPhone" label="联系方式" />
      <el-table-column prop="visitorInTime" label="到访时间" />
      <el-table-column prop="visitorOutTime" label="离开时间" />
      <el-table-column prop="communityName" label="小区" />
      <el-table-column prop="roomNumber" label="房号" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="openEditDialog(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="confirmDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="10"
         layout="prev, pager, next, ->, jumper, ->, sizes, total"
        :total="total"
      />
    </div>

    <!-- 新增/编辑访客的弹窗 -->
    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.visible"
      width="40%"
      @close="resetForm"
    >
      <el-form ref="visitorForm" :model="currentVisitor" label-width="100px">
        <el-form-item label="姓名">
          <el-input v-model="currentVisitor.visitorName" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="currentVisitor.visitorSex" placeholder="请选择性别">
            <el-option label="男" value="1" />
            <el-option label="女" value="00" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="currentVisitor.visitorPhone" placeholder="请输入联系方式" />
        </el-form-item>
          <el-form-item label="离开时间">
            <el-date-picker
              v-if="this.dialog.title === '新增访客'? '' : 'currentVisitor.visitorOutTime'"
              v-model="currentVisitor.visitorOutTime"
              type="date"
              placeholder="请选择时间"
              style="width: 100%;"
            />
          </el-form-item>
        <el-form-item label="证件号码">
          <el-input v-model="currentVisitor.homeownerIdcard" placeholder="请输入证件号码" />
        </el-form-item>
        <el-form-item label="所属小区">
          <el-select 
            v-model="currentVisitor.communityId" 
            placeholder="请选择小区"
            filterable
            clearable
            @change="handleCommunityChange"
          >
            <el-option
              v-for="item in communityOptions"
              :key="item.communityId"
              :label="item.communityName"
              :value="item.communityId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属楼栋">
          <el-select 
            v-model="currentVisitor.buildingId" 
            placeholder="请选择楼栋"
            filterable
            clearable
            @change="handleBuildingChange"
          >
            <el-option
              v-for="item in buildingOptions"
              :key="item.buildingId"
              :label="item.buildingName"
              :value="item.buildingId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房号">
          <el-select 
            v-model="currentVisitor.roomId" 
            placeholder="请选择房号"
            filterable
            clearable
          >
            <el-option
              v-for="item in roomOptions"
              :key="item.roomId"
              :label="item.roomNumber"
              :value="item.roomId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmVisitor">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>


export default {
  name: 'VisitorManagement',
  data() {
    return {
      currentPage: 0,
      pageSize: 10,
      total: 0,
      vednum: 1,//待访来客
      vingnum: 1,//当前访客
      vtatolnum: 1,//所有访客
      visitorTitle:'',
      tableData: [],
      dialog: {
        visible: false,
        title: '',
      },
      currentVisitor: {
        visitorName: '',
        visitorSex: '',
        visitorPhone: '',
        homeownerIdcard: '',
        visitorOutTime: '',
        communityId: '',
        buildingId: '',
        roomId: '',
      },
      // 新增数据选项
      communityOptions: [],
      buildingOptions: [],
      roomOptions: [],
    };
  },
  mounted(){
    this.getVisitorList(this.currentPage);
    this.getCommunityOptions();
  },

  methods: {
    // 获取小区选项
    async getCommunityOptions() {
      try {
        const response = await this.$axios.get('http://localhost:8080/community/selcomm');
        if (response.data.code === 200) {
          this.communityOptions = response.data.data;
        }
      } catch (error) {
        console.error('获取小区列表失败:', error);
        this.$message.error('获取小区列表失败');
      }
    },

    // 获取楼栋选项
    async getBuildingOptions(communityId) {
      if (!communityId) {
        this.buildingOptions = [];
        this.roomOptions = [];
        return;
      }
      try {
        const response = await this.$axios.get(`http://localhost:8080/building/bycommId`,{
          params: { commId:communityId }
        });
        if (response.data.code === 200) {
          this.buildingOptions = response.data.data;
        }
      } catch (error) {
        console.error('获取楼栋列表失败:', error);
        this.$message.error('获取楼栋列表失败');
      }
    },

    // 获取房号选项
    async getRoomOptions(buildingId) {
      if (!buildingId) {
        this.roomOptions = [];
        return;
      }
      try {
        const response = await this.$axios.get(`http://localhost:8080/room/roombybid`,{
          params: { buildingId:buildingId }
        });
        if (response.data.code === 200) {
          this.roomOptions = response.data.data;
        }
      } catch (error) {
        console.error('获取房号列表失败:', error);
        this.$message.error('获取房号列表失败');
      }
    },

    // 处理小区选择变化
    handleCommunityChange(value) {
      this.currentVisitor.buildingId = '';
      this.currentVisitor.roomId = '';
      this.getBuildingOptions(value);
    },

    // 处理楼栋选择变化
    handleBuildingChange(value) {
      this.currentVisitor.roomId = '';
      this.getRoomOptions(value);
    },

    // 获取访客列表
    async getVisitorList(pageNum) {
     await this.$axios.post('http://localhost:8080/visitor/all',{
        pageNum:pageNum,
        pageSize:this.pageSize,
        visitorTitle:this.visitorTitle,
        
      }).then(resp=>{
        console.log(resp);
        if (resp.data.code === 200) {
          this.vtatolnum = resp.data.data.vtatolnum;
          this.vingnum = resp.data.data.vingnum;
          this.vednum = resp.data.data.vednum;
          this.total = resp.data.data.total;
          this.currentPage = resp.data.data.current;
          this.tableData = resp.data.data.records.map(item => {
          return {
            ...item,
            // 格式化房号显示
            roomNumber: this.formatRoomNumber(item)
          };
        });
        }
      }).catch(error=>{
        console.log(error);
      });
    },

    // 格式化房号的方法
  formatRoomNumber(item) {
    if (item.buildingName && item.unitId && item.roomNumber) {
      return `${item.buildingName}${item.unitId}单元${item.roomNumber}`;
    } else if (item.roomNumber) {
      return item.roomNumber;
    } else {
      return '-';
    }
  },

    // 打开新增访客的对话框
    openAddDialog() {
      this.dialog.title = '新增访客';
      this.dialog.visible = true;
    },

    // 打开编辑访客的对话框
openEditDialog(row) {
  this.dialog.title = '编辑访客';
  this.dialog.visible = true;
  this.getVisitorInfo(row.visitorId);
  console.log(this.currentVisitor);
  
  // 如果编辑时有小区ID，则加载对应的楼栋和房号
  if (row.communityId) {
    this.getBuildingOptions(row.communityId);
    if (row.buildingId) {
      this.getRoomOptions(row.buildingId);
    }
  }
},

//根据访客id获取访客信息
async getVisitorInfo(visitorId) {
   try {
      const resp = await this.$axios.get('http://localhost:8080/visitor/byid', {
        params: { visitorId: visitorId }
      });
      
      if (resp.data.code === 200) {
        console.log(resp.data.data);
        
        const row = resp.data.data;
        this.currentVisitor = { 
          ...row,
          visitorName: row.visitorName,
          visitorSex: row.visitorSex,
          visitorPhone: row.visitorPhone,
          visitorInTime: row.visitorInTime,
          homeownerIdcard: row.homeownerIdcard,
          // 格式化离开时间
          visitorOutTime: row.visitorOutTime ? this.formatDate(new Date(row.visitorOutTime)) : '',
          communityId: row.communityId,
          buildingId: row.buildingId,
          roomId: row.roomId
        };
      } else {
        this.$message.error('获取访客信息失败');
      }
    } catch (error) {
      console.error('获取访客信息失败:', error);
      this.$message.error('获取访客信息失败');
    }
},

// 确定提交新增或编辑的访客信息
async confirmVisitor() {
  if (this.dialog.title === '新增访客') {
    console.log(this.currentVisitor);
    
    // 发送新增访客请求
    await this.$axios.post('http://localhost:8080/visitor/addvisitor', this.currentVisitor)
     .then(response => {
      if (response.data.code === 200) {
        this.$message.success('新增访客成功');
        this.dialog.visible = false;
        this.getVisitorList(this.currentPage);
      } else {
        this.$message.error('新增访客失败');
      }
  }).catch(error => {
    console.error('新增访客失败:', error);
    this.$message.error('新增访客失败');
  });
  } else {
    // 编辑时处理时间格式，确保后端能正确接收
    const submitData = {
      ...this.currentVisitor,
      // 如果visitorOutTime存在，确保格式正确
      visitorOutTime: this.currentVisitor.visitorOutTime ? this.formatDateForSubmit(this.currentVisitor.visitorOutTime) : null
    };
    
    // 发送修改访客请求
    await this.$axios.post('http://localhost:8080/visitor/updatevisitor', submitData)
     .then(response => {
      if (response.data.code === 200) {
        this.$message.success('修改访客成功');
        this.dialog.visible = false;
        this.getVisitorList(this.currentPage);
      } else {
        this.$message.error('修改访客失败');
      }
    }).catch(error => {
      console.error('修改访客失败:', error);
      this.$message.error('修改访客失败');
    });
  }
},

// 使用JavaScript内置的Date对象进行格式化（用于显示）
formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
},

// 专门用于提交数据的时间格式化方法
formatDateForSubmit(dateString) {
  if (!dateString) return null;
  
  // 如果已经是Date对象
  if (dateString instanceof Date) {
    return this.formatDate(dateString);
  }
  
  // 如果是字符串，尝试解析
  const date = new Date(dateString);
  if (isNaN(date.getTime())) {
    // 如果解析失败，返回原字符串或当前时间
    return dateString;
  }
  
  return this.formatDate(date);
},

    // 重置表单
    resetForm() {
      this.currentVisitor = {
        visitorName: '',
        visitorSex: '',
        visitorPhone: '',
        homeownerIdcard: '',
        visitorOutTime: '',
        communityId: '',
        buildingId: '',
        roomId: '',
      };
      this.buildingOptions = [];
      this.roomOptions = [];
    },

    // 确认删除访客
    async confirmDelete(row) {
      try {
        const confirmResult = await this.$confirm('是否确认删除该访客?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        if (confirmResult === 'confirm') {
          // 发送删除访客请求
          const response = await this.$axios.delete(`http://localhost:8080/visitor/delvisitor`, {
            params: { visitorId: row.visitorId }
          });
          if (response.data.code === 200) {
            this.$message.success('删除成功');
            this.getVisitorList(this.currentPage);
          } else {
            this.$message.error('删除失败');
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除访客失败', error);
          this.$message.error('删除失败，请重试');
        }
      }
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.getVisitorList(1);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getVisitorList(this.currentPage);
    },
  },
};
</script>

<style scoped>
.visitor-management {
  padding: 20px;
}

.stats-cards {
  display: flex;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  text-align: center;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-right: 20px;
}

.stat-card:last-child {
  margin-right: 0;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  color: #409EFF;
  font-weight: bold;
}

.add-card {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}

.add-card:hover {
  border-color: #409EFF;
  background-color: #f5f7fa;
}

.stat-icon {
  font-size: 24px;
  color: #606266;
}

.search-bar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 15px;
}

.search-bar .el-input {
  margin-right: 8px;
}

/* 分页居右样式 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.add-btn {
  margin-bottom: 20px;
}
</style>